import socket
import os

# 设置服务器的IP和端口
SERVER_IP = '0.0.0.0'  # 监听所有网络接口
SERVER_PORT = 5001

# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定IP和端口
server_socket.bind((SERVER_IP, SERVER_PORT))

# 监听连接
server_socket.listen(5)
print(f'服务器启动，监听端口 {SERVER_PORT}...')

# 处理客户端连接
def handle_client(client_socket):
    # 接收文件名和大小
    file_info = client_socket.recv(1024).decode('utf-8')
    filename, filesize = file_info.split(',')
    filename = os.path.basename(filename)
    filesize = int(filesize)

    # 打开文件准备写入
    with open(filename, 'wb') as f:
        bytes_received = 0
        while bytes_received < filesize:
            # 每次接收4096字节数据
            bytes_read = client_socket.recv(4096)
            if not bytes_read:
                break
            f.write(bytes_read)
            bytes_received += len(bytes_read)
            print(f'接收中... {bytes_received / filesize * 100:.2f}%')

    print(f'文件接收完成：{filename}')
    client_socket.close()

while True:
    client_sock, addr = server_socket.accept()
    print(f'连接来自：{addr}')
    handle_client(client_sock)
